module.exports = function (data, args) {
    data = data || [], args = args || {};
    //根Id
    var rootId = args.rootId || '0';
    //id 字段别名
    var idKey = args.idKey || 'id';
    //parentId 父级字段别名
    var parentIdKey = args.parentIdKey || 'parentId';
    
    var rc = {};
    rc['_' + rootId] = { children:[] }
    var times = 0;
    while (times != -1) {
        var num = 0;
        for (var i = 0; i < data.length; i++) {
            if (times == 0) {
                data[i].children = [];
                rc['_' + data[i][idKey]] = data[i];
                if (data[i][parentIdKey] == rootId) {
                    data[i].added = true;
                    rc['_' + rootId].children.push(data[i]);
                    num++;
                }
            } else if (!data[i].added) {
                if (rc['_' + data[i][parentIdKey]]) {
                    data[i].added = true;
                    rc['_' + data[i][parentIdKey]].children.push(data[i])
                    num++;
                }
            }
        }
        times = num == 0 ? -1 : (times + 1);
    }
    function sort(array) {
        if (typeof array.sort == 'function') {
            array.sort(function (a, b) {
                if (!a.sorted) {
                    a.sorted = true;
                    sort(a.children);
                }
                if (!b.sorted) {
                    b.sorted = true;
                    sort(b.children);
                }
                return args.sort(a, b);
            })
        }
    }
    if (args.sort) sort(rc['_' + rootId].children);
    return rc['_' + rootId].children;
}